# -*- coding: utf-8 -*-
import sys
from PySide import QtGui
from PySide import QtNetwork


class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.init_ui()
        self.init_socket()

    def init_ui(self):
        self.setWindowTitle(u'客户端')
        self.info = QtGui.QTextEdit()
        self.info.setReadOnly(True)
        self.send_text = QtGui.QTextEdit()
        self.btn = QtGui.QPushButton(u'发送')
        self.btn.clicked.connect(self.send_msg)
        self.client_box = QtGui.QListWidget()

        left = QtGui.QVBoxLayout()
        left.addWidget(self.info)
        left.addWidget(self.send_text)
        left_bottom = QtGui.QHBoxLayout()
        left_bottom.addStretch()
        left_bottom.addWidget(self.btn)
        left.addLayout(left_bottom)
        main = QtGui.QHBoxLayout()
        main.addLayout(left)
        main.addWidget(self.client_box)
        self.setLayout(main)

    def init_socket(self):
        self.client = QtNetwork.QTcpSocket()
        self.client.connectToHost(QtNetwork.QHostAddress('192.168.1.102'), 60000)
        self.client.readyRead.connect(self.recv)

    def recv(self):
        data = self.sender().readAll().data().decode('utf-8')
        self.info.append(data)

    def send_msg(self):
        buf = self.send_text.toPlainText()
        self.client.write(buf.encode('utf-8'))
        self.info.append(u'[自己]说: %s' % buf)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    widget = Window()
    widget.show()
    sys.exit(app.exec_())
